<?php
namespace app\api\controller\v1;

use app\common\controller\Api;
use think\Db;
use think\Request;
use think\Validate;

class Cooperative extends Api
{
    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';

    protected function ensureTables()
    {
        $sql = "CREATE TABLE IF NOT EXISTS `fa_cooperative_intent` (
            `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
            `user_id` int(10) unsigned NOT NULL DEFAULT 0 COMMENT '用户ID[index]',
            `name` varchar(50) NOT NULL DEFAULT '' COMMENT '姓名[key,index,type:text]',
            `phone` varchar(20) NOT NULL DEFAULT '' COMMENT '手机号码[key,type:text]',
            `wechat` varchar(50) NOT NULL DEFAULT '' COMMENT '微信号[type:text]',
            `content` text COMMENT '合作内容[type:text]',
            `create_time` datetime DEFAULT NULL COMMENT '创建时间[type:datetime]',
            `update_time` datetime DEFAULT NULL COMMENT '更新时间[type:datetime]',
            `delete_time` datetime DEFAULT NULL COMMENT '删除时间[type:datetime]',
            `weigh` int(10) NOT NULL DEFAULT 0 COMMENT '权重',
            `status` int(10) NOT NULL DEFAULT 1 COMMENT '状态[type:radio,content:1=正常|0=关闭]',
            PRIMARY KEY (`id`),
            KEY `idx_user` (`user_id`),
            KEY `idx_status` (`status`)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci COMMENT='合作意向'";
        Db::execute($sql);
    }

    public function save(Request $request)
    {
        $this->ensureTables();
        $user = $this->auth->getUser(true);
        $uid = isset($user['uid']) ? $user['uid'] : 0;
        $data = $_POST;
        $validate = new Validate();
        $validate->rule([
            'name' => 'require|max:50',
            'phone' => ['require','regex'=>'/^1[3-9]\\d{9}$/'],
            'wechat' => 'max:50',
            'content' => 'require|max:2000',
        ]);
        if (!$validate->check($data)) {
            return json(['code' => 0, 'msg' => $validate->getError()]);
        }
        $data['user_id'] = $uid;
        $now = date('Y-m-d H:i:s');
        $data['create_time'] = $now;
        $data['update_time'] = $now;
        $data['status'] = 1;
        $data['weigh'] = 0;
        $id = Db::name('fa_cooperative_intent')->insertGetId($data);
        file_put_contents($_SERVER["DOCUMENT_ROOT"]."/../cooperative_submit.log", json_encode(['time'=>$now,'uid'=>$uid,'data'=>$data], JSON_UNESCAPED_UNICODE)."\\n", FILE_APPEND);
        return json(['code' => 200, 'msg' => '提交成功', 'data' => ['id' => $id]]);
    }
}